package com.bishe.demo.modules.account.service.impl;

import com.bishe.demo.modules.account.dao.RoleDao;
import com.bishe.demo.modules.account.dao.RoleResourceDao;
import com.bishe.demo.modules.account.dao.UserRoleDao;
import com.bishe.demo.modules.account.entity.Role;
import com.bishe.demo.modules.account.service.RoleService;
import com.bishe.demo.modules.common.entity.ResultEntity;
import com.bishe.demo.modules.common.entity.SearchBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Collections;
import java.util.List;
import java.util.Optional;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserRoleDao userRoleDao;

    @Autowired
    private RoleResourceDao roleResourceDao;

    @Override
    @Transactional
    public ResultEntity<Role> insertRole(Role role) {
        roleDao.insertRole(role);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.code, "添加成功", role);
    }

    @Override
    @Transactional
    public ResultEntity<Role> updateRole(Role role) {
        roleDao.updateRole(role);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.code, "修改成功", role);
    }

    @Override
    @Transactional
    public ResultEntity<Role> deleteRoleByRoleId(int roleId) {
        if (roleId == 1) {
            return new ResultEntity<Role>(ResultEntity.ResultStatus.FAILED.code, "不允许删除管理员角色");
        }
        roleDao.deleteRoleByRoleId(roleId);
        userRoleDao.deleteUserRoleByRoleId(roleId);
        roleResourceDao.deleteRoleResourceByRoleId(roleId);
        return new ResultEntity<Role>(ResultEntity.ResultStatus.SUCCESS.code, "删除成功");
    }

    @Override
    public Role getRoleByRoleId(int roleId) {
        return roleDao.getRoleByRoleId(roleId);
    }

    @Override
    public Role getRoleByUserId(int userId) {
        return roleDao.getRoleByUserId(userId);
    }

    @Override
    public List<Role> getRoles() {
        return Optional.ofNullable(roleDao.getRoles()).orElse(Collections.emptyList());
    }

    @Override
    public PageInfo<Role> getRolesBySearchBean(SearchBean searchBean) {
        searchBean.initSearchBean();
        PageHelper.startPage(searchBean.getCurrentPage(), searchBean.getPageSize());
        return new PageInfo<Role>(Optional
                .ofNullable(roleDao.getRolesBySearchBean(searchBean))
                .orElse(Collections.emptyList()));
    }
}
